package admin

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"jwgin/model/mysql"
	"jwgin/service"
)

type gift struct{}

func (l *gift) Routers(Router *gin.RouterGroup) (R gin.IRoutes) {
	//资源列表
	Router.GET("gift", l.get)   //列表
	Router.POST("gift", l.post) //更新
	Router.PUT("gift", l.put)   //新加
	return Router
}

func (l *gift) get(c *gin.Context) {
	count, size, offset := pages(c)
	ret := []mysql.Gift{}
	//创建DB
	db := service.G.Model(&mysql.Gift{})

	//名字
	if name := c.Query("name"); name != "" {
		db = db.Where("name = ?", name)
	}

	//状态
	if statu := c.Query("statu"); statu != "" {
		db = db.Where("statu = ?", statu)
	}

	err := db.Count(&count).Offset(offset).Limit(size).Find(&ret).Error
	if err != nil {
		RespErr(c, err)
		return
	}
	RespList(c, count, ret)
}
func (l *gift) post(c *gin.Context) {
	q := &mysql.Gift{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, err)
		return
	}

	if q.Id < 1 {
		RespErr(c, fmt.Errorf("参数错误"))
		return
	}

	err := service.G.Save(q).Error
	if err != nil {
		RespErr(c, err)
		return
	}
	RespSucc(c, nil)
}
func (l *gift) put(c *gin.Context) {
	q := &mysql.Gift{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, err)
		return
	}
	if err := service.G.Create(q).Error; err != nil {
		RespErr(c, err)
	} else {
		RespSucc(c, nil)
	}
}
